package com.ja.openchat.ui.found;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.services.core.PoiItem;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.data.NotShowPoiItem;
import com.ja.openchat.data.entity.UserInfoMultiEntity;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.ui.chat.MobileContactHomeActivity;
import com.ja.openchat.ui.chat.PreviewLocalMediaActivity;
import com.ja.openchat.views.SimpleTextWatcher;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupAnimation;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.zy.openchat.App;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.circle.CircleTopicInfo;
import com.zy.openchat.core.model.circle.MediaInfo;
import com.zy.openchat.core.model.circle.UserTags;
import com.zy.openchat.core.model.circle.VisibleTypeInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.TextEntity;
import com.zy.openchat.core.model.message.TextEntityType;
import com.zy.openchat.core.model.message.VideoParam;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.core.model.video.UploadMedioInfo;
import com.zy.openchat.util.CaptureStrategy;
import com.zy.openchat.util.CircleMentionSpan;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.DensityUtil;
import com.zy.openchat.util.FileUtils;
import com.zy.openchat.util.MediaFile;
import com.zy.openchat.util.MediaStoreCompat;
import com.zy.openchat.util.MediaUtils;
import com.zy.openchat.util.MyItemTouchCallback;
import com.zy.openchat.util.OnRecyclerItemClickListener;
import com.zy.openchat.util.compress.util.VideoProgressListener;
import com.zy.openchat.util.glide.GlideApp;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.bzcoder.mediapicker.config.Constant;

public class PostCircleActivity extends JaBaseActivity implements PostCircleMediaCallback {

    public static void startActivity(Context context, ArrayList<MediaInfo> mediaInfos) {
        Intent intent = new Intent(context, PostCircleActivity.class);
        intent.putExtra("medias", mediaInfos);
        context.startActivity(intent);
    }

    public static void choosePostCircleMedia(MediaStoreCompat mediaStoreCompat, FragmentActivity activity) {
        choosePostCircleMedia(mediaStoreCompat, activity, false, 0);
    }


    public static void choosePostCircleMedia(final MediaStoreCompat mediaStoreCompat, FragmentActivity activity, boolean isOnlyType, int maxImageCount) {
        String[] data;
        if (isOnlyType) {
            data = new String[]{activity.getString(R.string.shoot_text), activity.getString(R.string.select_from_album)};
        } else {
            data = new String[]{
                    String.format("%s-%s", activity.getString(R.string.shoot_text), activity.getString(R.string.photo_text)),
                    String.format("%s-%s", activity.getString(R.string.shoot_text), activity.getString(R.string.video_text)),
                    activity.getString(R.string.select_from_album)};
        }
        new XPopup.Builder(activity)
                .asBottomList(null, data, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        if (isOnlyType) {
                            if (position == 0) {
                                mediaStoreCompat.setCaptureStrategy(new CaptureStrategy(true, App.getInstanse().getPackageName() + ".utilcode.fileprovider", Constants.userImagePath()));
                                activity.startActivityForResult(mediaStoreCompat.dispatchCaptureImageIntent(activity), 101);
                            } else {
                                MediaUtils.chooseAlbum(activity, false, maxImageCount, 0, 3 * 60 * 1000);
                            }
                        } else {
                            if (position < 2) {
                                if (position == 0) {
                                    mediaStoreCompat.setCaptureStrategy(new CaptureStrategy(true, App.getInstanse().getPackageName() + ".utilcode.fileprovider", Constants.userImagePath()));
                                    activity.startActivityForResult(mediaStoreCompat.dispatchCaptureImageIntent(activity), 101);
                                } else {
                                    mediaStoreCompat.setCaptureStrategy(new CaptureStrategy(true, App.getInstanse().getPackageName() + ".utilcode.fileprovider", Constants.userVideoPath()));
                                    activity.startActivityForResult(mediaStoreCompat.dispatchCaptureVideoIntent(activity), 102);
                                }
                            } else {
                                MediaUtils.chooseAlbum(activity, false, Constants.MAX_CIRCLE_IMAGE_COUNT, 1, 3 * 60 * 1000);
                            }
                        }
                    }
                }).show();
    }

    public static void onActivityResultForPostCircleMedia(MediaStoreCompat mediaStoreCompat, Activity activity, int requestCode, int resultCode, Intent data, PostCircleMediaCallback callback) {
        if (data == null && requestCode != 101) {
            return;
        }
        ArrayList<MediaInfo> mediaInfos = new ArrayList<>();
        if (requestCode == Constant.REQUEST_CODE_CHOOSE) {
            List<String> albums = MediaUtils.getResultAlbumData(activity, requestCode, resultCode, data);
            if (albums != null && albums.size() > 0) {
                for (String localPah : albums) {
                    MediaInfo mediaInfo = new MediaInfo();
                    mediaInfo.setMediaPath(localPah);
                    if (MediaFile.isVideoFileType(MediaFile.getFileType(localPah).fileType)) {
                        mediaInfo.setVideo(true);
                        VideoParam videoParam = MediaUtils.getVideoParam(localPah);
                        if (videoParam != null) {
                            mediaInfo.setWidth(videoParam.getWidth());
                            mediaInfo.setHeight(videoParam.getHeight());
                            mediaInfo.setDuration(videoParam.getDuration());
                        }
                    } else {
                        mediaInfo.setVideo(false);
                    }
                    mediaInfos.add(mediaInfo);
                }
                callback.onSuccess(mediaInfos);
                return;
            }
        }
        if (mediaStoreCompat != null) {
            if (requestCode == 101 && !TextUtils.isEmpty(mediaStoreCompat.onActivityResultForImage(data))) {
                String imagePath = mediaStoreCompat.onActivityResultForImage(data);
                if (TextUtils.isEmpty(imagePath) || !new File(imagePath).exists()) {
                    return;
                }
                MediaInfo mediaInfo = new MediaInfo();
                mediaInfo.setMediaPath(imagePath);
                mediaInfo.setVideo(false);
                mediaInfos.add(mediaInfo);
                callback.onSuccess(mediaInfos);
                return;
            }
            if (requestCode == 102 && !TextUtils.isEmpty(mediaStoreCompat.onActivityResultForVideo(data))) {
                String localPah = mediaStoreCompat.onActivityResultForVideo(data);
                MediaInfo mediaInfo = new MediaInfo();
                mediaInfo.setMediaPath(localPah);
                mediaInfo.setVideo(true);
                VideoParam videoParam = MediaUtils.getVideoParam(localPah);
                if (videoParam != null) {
                    mediaInfo.setWidth(videoParam.getWidth());
                    mediaInfo.setHeight(videoParam.getHeight());
                    mediaInfo.setDuration(videoParam.getDuration());
                }
                mediaInfos.add(mediaInfo);
                callback.onSuccess(mediaInfos);
                return;
            }
        }
        callback.onCancle();

    }

    @BindView(R.id.post_content)
    EditText post_content;
    @BindView(R.id.photos_view_group)
    RecyclerView photos_view_group;
    @BindView(R.id.user_view_group)
    RecyclerView user_view_group;
    @BindView(R.id.add_user_btn)
    View add_user_btn;
    @BindView(R.id.who_look_tx)
    TextView who_look_tx;
    @BindView(R.id.title_look)
    TextView title_look;
    @BindView(R.id.location_tx)
    TextView location_tx;
    @BindView(R.id.tv_ok_right)
    TextView tv_ok_right;
    @BindView(R.id.fouceBtn)
    TextView fouceBtn;
    @BindView(R.id.topicBtn)
    TextView topicBtn;

    private CircleUserGridAdapter circleUserAdapter;


    private List<MediaInfo> totalMediaInfos = new ArrayList<>();
    private ArrayList<UserInfo> mChooseUsers = new ArrayList<>();
    private ArrayList<UserInfoMultiEntity> mChooseUsersMulti = new ArrayList<>();
    private MediaStoreCompat mediaStoreCompat;
    private int topicStartIndex = -1;
    @Override
    public void initData() {
        setTitle(getString(R.string.circle_text));
        tv_ok_right.setVisibility(View.VISIBLE);
        tv_ok_right.setText(getString(R.string.post_text));
        tv_ok_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBlog();
            }
        });
        addMediaBtnInfo.setAddBtnType(true);
        if (getIntent().getSerializableExtra("medias") != null) {
            ArrayList<MediaInfo> mediaInfos = (ArrayList<MediaInfo>) getIntent().getSerializableExtra("medias");
            if (mediaInfos != null && mediaInfos.size() > 0) {
                notifyMediaInfo(mediaInfos);
                totalMediaInfos.addAll(mediaInfos);
                if (!mediaInfos.get(0).isVideo() && mediaInfos.size() < Constants.MAX_CIRCLE_IMAGE_COUNT) {
                    totalMediaInfos.add(addMediaBtnInfo);
                }
            }
        }

        photos_view_group.setLayoutManager(new GridLayoutManager(this, 3));
        photos_view_group.setAdapter(chooseAdapter);
        chooseAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                MediaInfo mediaInfo = chooseAdapter.getItem(position);
                if ((position + 1) == chooseAdapter.getItemCount() && mediaInfo.isAddBtnType()) {
                    if (mediaStoreCompat == null) {
                        mediaStoreCompat = new MediaStoreCompat(PostCircleActivity.this);
                    }
                    boolean isOnlyType = true;
                    if (chooseAdapter.getItemCount() == 1 && chooseAdapter.getItem(0).isAddBtnType()) {
                        isOnlyType = false;
                    }
                    choosePostCircleMedia(mediaStoreCompat, PostCircleActivity.this, isOnlyType, Constants.MAX_CIRCLE_IMAGE_COUNT - chooseAdapter.getItemCount() + 1);
                } else {
                    List<MediaInfo> mediaInfos = chooseAdapter.getData();
                    if (mediaInfos.contains(addMediaBtnInfo)) {
                        mediaInfos = mediaInfos.subList(0, mediaInfos.size() - 1);
                    }
                    PreviewLocalMediaActivity.previewMedia(PostCircleActivity.this, mediaInfos, position);
                }
            }
        });
        final ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new MyItemTouchCallback(chooseAdapter));
        itemTouchHelper.attachToRecyclerView(photos_view_group);

        photos_view_group.addOnItemTouchListener(new OnRecyclerItemClickListener(photos_view_group) {
            @Override
            public void onLongClick(RecyclerView.ViewHolder vh) {
                if (!totalMediaInfos.contains(addMediaBtnInfo)||vh.getLayoutPosition()!=totalMediaInfos.size()-1) {
                    itemTouchHelper.startDrag(vh);
                }
            }
        });
        user_view_group.setLayoutManager(new GridLayoutManager(this, 5));
        mChooseUsersMulti.clear();
        UserInfoMultiEntity userInfoMultiEntity = new UserInfoMultiEntity();
        userInfoMultiEntity.itemType=1;
        mChooseUsersMulti.add(userInfoMultiEntity);
        circleUserAdapter = new CircleUserGridAdapter(mChooseUsersMulti);
        user_view_group.setAdapter(circleUserAdapter);
        circleUserAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_add:
                        startActivityForResult(MobileContactHomeActivity.getActivityForResult(PostCircleActivity.this, 3, mChooseUsers),REQUEST_USERS);
                        break;
                }
            }
        });
        fouceBtn.setText(getString(R.string.mention_at_text));

        post_content.setMovementMethod(LinkArrowKeyMovementMethod.getInstance());
        post_content.addTextChangedListener(new SimpleTextWatcher(){
            int input_end = -1;
            @Override
            public void afterTextChanged(Editable s) {
                if (input_end>=0&&topicStartIndex>=0 &&s.length()>=input_end && input_end > topicStartIndex&&s.charAt(topicStartIndex) == '#') {
                    replaceTopicInfo(new CircleTopicInfo(0,s.subSequence(topicStartIndex+1,input_end).toString()),topicStartIndex,input_end);
                    input_end = -1;
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (PostCircleActivity.this.getCurrentFocus() == post_content) {
                    if (before == 0 && count == 1) {
                        if(s.charAt(start) == '@'){
                            startActivityForResult(MobileContactHomeActivity.getActivityForResult(PostCircleActivity.this, 1, null), REQUEST_AT_LOOK_WITH_SIGN);
                        }else if(s.charAt(start) == '#'){
                            topicStartIndex = start;
                            showTopicDialog(true,post_content);
                        }else if(topicStartIndex>=0&&(s.charAt(start) == ' '
                                ||s.charAt(start) == '\n')){
                            if(topicStartIndex<s.length()
                                    &&topicStartIndex<(start-1)
                                    &&s.charAt(topicStartIndex) == '#'){
                                replaceTopicInfo(new CircleTopicInfo(0,s.subSequence(topicStartIndex+1,start).toString()),topicStartIndex,start);
                            }
                        }else if(topicStartIndex>=0&&(start-topicStartIndex)>=Constants.CIRCLE_TOPIC_MAX_WORD_COUNT){
                            input_end = start+count;
                            if((input_end-topicStartIndex-1)>Constants.CIRCLE_TOPIC_MAX_WORD_COUNT){
                                input_end = topicStartIndex + Constants.CIRCLE_TOPIC_MAX_WORD_COUNT+1;
                            }
                        }
                    }else{
                        if(topicStartIndex>=0){
                            if((start+count-1-topicStartIndex)>=Constants.CIRCLE_TOPIC_MAX_WORD_COUNT){
                                input_end = start+count;
                                if((input_end-topicStartIndex-1)>Constants.CIRCLE_TOPIC_MAX_WORD_COUNT){
                                    input_end = topicStartIndex + Constants.CIRCLE_TOPIC_MAX_WORD_COUNT+1;
                                }
                            }
                        }else if(before != count){
                            String input = s.subSequence(start,start+count).toString();
                            if(!TextUtils.isEmpty(input)&&input.contains("#")){
                                topicStartIndex = start+input.indexOf("#");
                                if((start+count-1-topicStartIndex)>=Constants.CIRCLE_TOPIC_MAX_WORD_COUNT){
                                    input_end = start+count;
                                    if((input_end-topicStartIndex-1)>Constants.CIRCLE_TOPIC_MAX_WORD_COUNT){
                                        input_end = topicStartIndex + Constants.CIRCLE_TOPIC_MAX_WORD_COUNT+1;
                                    }
                                }
                            }
                        }

                    }

                    // delete
                    if (before == 1 && count == 0) {
                        Editable text = post_content.getText();
                        CircleMentionSpan[] spans = text.getSpans(0, text.length(), CircleMentionSpan.class);
                        if (spans != null) {
                            for (CircleMentionSpan span : spans) {
                                if (text.getSpanEnd(span) == start && text.getSpanFlags(span) == Spanned.SPAN_INCLUSIVE_EXCLUSIVE) {
                                    text.delete(text.getSpanStart(span), text.getSpanEnd(span));
                                    text.removeSpan(span);
                                    break;
                                } else if (start >= text.getSpanStart(span) && start < text.getSpanEnd(span)) {
                                    text.removeSpan(span);
                                    break;
                                }
                            }
                        }
                    }

                    // insert
                    if (before == 0 && count > 0) {
                        Editable text = post_content.getText();
                        CircleMentionSpan[] spans = text.getSpans(0, text.length(), CircleMentionSpan.class);
                        if (spans != null) {
                            for (CircleMentionSpan span : spans) {
                                if (start >= text.getSpanStart(span) && start < text.getSpanEnd(span)) {
                                    text.removeSpan(span);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        });
        loadTopicInfos(false);
    }

    private PoiItem choosePoiItem = new NotShowPoiItem();
    private int chooseWhoLookType = WhoLookActivity.WHO_LOOK_TYPE_PUBLIC_ALL;
    private ArrayList<UserInfo> chooseUsers;
    private ArrayList<ChatInfo> groupInfos;
    private ArrayList<UserTags> chooseTags;
    private ProgressDialog progressDialog = null;

    public void sendBlog(){
        if(Common.isEmpty(totalMediaInfos)){
            return;
        }
        List<MediaInfo> mediaInfos = new ArrayList<>();
        mediaInfos.addAll(totalMediaInfos);
        mediaInfos.remove(addMediaBtnInfo);
        if(Common.isEmpty(mediaInfos)){
            showErrorTip(getString(R.string.select_photo_or_video));
            return;
        }
        if(mediaInfos.get(0).isVideo()){
            showProgress();
            GlideApp
                    .with(PostCircleActivity.this)
                    .asBitmap()
                    .load(mediaInfos.get(0).getMediaPath())
                    .into(new SimpleTarget<Bitmap>(){
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            hideProgress();
                            progressDialog = null;
                            if(progressDialog==null){
                                progressDialog = new ProgressDialog(PostCircleActivity.this);
                                progressDialog.setTitle(null);
                                progressDialog.setCancelable(false);
                                progressDialog.setCanceledOnTouchOutside(false);
                                progressDialog.setMessage(getString(R.string.compressed_video_text));
                                progressDialog.setIndeterminate(false);
                                progressDialog.setMax(10000);
                                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                progressDialog.setProgress(0);
                                progressDialog.show();
                            }
                            Observable.create(new ObservableOnSubscribe<UploadMedioInfo>() {
                                @Override
                                public void subscribe(@NonNull ObservableEmitter<UploadMedioInfo> emitter) throws Exception {
                                    mediaInfos.get(0).setThumbnail(saveBitmap(PostCircleActivity.this,resource));
                                    emitter.onNext(UploadMedioInfo.compressVideo(PostCircleActivity.this, mediaInfos.get(0).getMediaPath(), new VideoProgressListener() {
                                        UploadMedioInfo compress = UploadMedioInfo.newVideoProgress();
                                        @Override
                                        public void onProgress(float progress) {
                                            compress.videoCompressProgress = progress*10000;
                                            emitter.onNext(compress);
                                        }
                                    }));
                                    emitter.onComplete();
                                }
                            }).subscribeOn(Schedulers.newThread())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new Consumer<UploadMedioInfo>() {
                                        @Override
                                        public void accept(UploadMedioInfo first) throws Exception {
                                            if (first.isCompressFinish) {
                                                mediaInfos.get(0).setMediaPath(first.mediaPath);
                                                showProgress();
                                                sendBlog(mediaInfos);
                                            } else {
                                                if (progressDialog != null) {
                                                    progressDialog.setProgress((int) first.videoCompressProgress);
                                                }
                                            }

                                        }
                                    }, new Consumer<Throwable>() {
                                        @Override
                                        public void accept(Throwable throwable) throws Exception {
                                            sendBlog(mediaInfos);
                                            if (progressDialog != null) {
                                                progressDialog.dismiss();
                                                progressDialog = null;
                                            }
                                        }
                                    }, new Action() {
                                        @Override
                                        public void run() throws Exception {
                                            if (progressDialog != null) {
                                                progressDialog.dismiss();
                                                progressDialog = null;
                                            }
                                        }
                                    });
                        }
                    });

        }else{
            showProgress();
            sendBlog(mediaInfos);
        }
    }

    public static String saveBitmap(Context context, Bitmap bitmap) {
        String displayName = "image_" + Common.getCurrentFormatTime() + ".jpg";
        OutputStream outStream = null;
        File dir = new File(Constants.userImagePath());
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(Constants.userImagePath(), displayName);//创建文件，第一个参数为路径，第二个参数为文件名
        Uri uri;
        try {
            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.close();
            if (Build.VERSION.SDK_INT >= 24) {
                uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
            } else {
                uri = Uri.fromFile(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }


    private void sendBlog(List<MediaInfo> mediaInfos) {
        Editable content = post_content.getText();
        String sendContent = "";
        List<Long> mention_ids = new ArrayList<>();
        List<String> topics = new ArrayList<>();
        List<TextEntity> entities = new ArrayList<>();
        if (!TextUtils.isEmpty(content)) {
            sendContent = content.toString();
            CircleMentionSpan[] mentions = content.getSpans(0, content.length(), CircleMentionSpan.class);
            if (mentions != null && mentions.length > 0) {
                for (CircleMentionSpan span : mentions) {
                    int start = content.getSpanStart(span);
                    int end = content.getSpanEnd(span);
                    int length = end-start;
                    if(span.isUserType()){
                        entities.add(new TextEntity(length,start,span.getUid()));
                        mention_ids.add(span.getUid());
                    }else{
                        entities.add(new TextEntity(length,start, TextEntityType.CircleTopicType));
                        topics.add(span.getTopic());
                    }
                }
            }

        }
        TelegramManager.getTelegramManager().sendBlog(this, sendContent,entities
                , mediaInfos, mention_ids,topics, choosePoiItem
                , new VisibleTypeInfo(chooseWhoLookType, chooseUsers, groupInfos, chooseTags), new TgResultBlock<TgResponse>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
//                        if(!Common.isEmpty(mediaInfos)&&mediaInfos.get(0).isVideo()&&!TextUtils.isEmpty(mediaInfos.get(0).getThumbnail())){
//                            FileUtils.delete(mediaInfos.get(0).getThumbnail());
//                        }
                        hideProgress();
                        if (obj.ok) {
                            ToastUtils.showShort(getString(R.string.publish_success));
                            finish();
                        } else {
                            showErrorTip(obj.errString);
                        }
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {
                        if (!Common.isEmpty(mediaInfos) && mediaInfos.get(0).isVideo() && !TextUtils.isEmpty(mediaInfos.get(0).getThumbnail())) {
                            FileUtils.delete(mediaInfos.get(0).getThumbnail());
                        }
                        hideProgress();
                        showErrorTip(getString(R.string.request_error));
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_USERS) {
            if (data != null && data.getSerializableExtra("users") != null) {
                ArrayList<UserInfo> chooseUserInfos = (ArrayList<UserInfo>) data.getSerializableExtra("users");
                mChooseUsers.clear();
                mChooseUsersMulti.clear();
                mChooseUsers.addAll(chooseUserInfos);
                for (int i = 0; i < mChooseUsers.size(); i++) {
                    UserInfoMultiEntity userInfoMultiEntity = new UserInfoMultiEntity();
                    userInfoMultiEntity.userInfo = mChooseUsers.get(i);
                    mChooseUsersMulti.add(userInfoMultiEntity);
                }
                UserInfoMultiEntity userInfoMultiEntity = new UserInfoMultiEntity();
                userInfoMultiEntity.itemType=1;
                mChooseUsersMulti.add(userInfoMultiEntity);
                circleUserAdapter.notifyDataSetChanged();
            }
        } else if(requestCode == REQUEST_AT_LOOK){
            if (data != null && data.getSerializableExtra("users") != null) {
                ArrayList<UserInfo> chooseUserInfos = (ArrayList<UserInfo>) data.getSerializableExtra("users");

                Editable editable = post_content.getEditableText();
                int endPosition;
                editable.append(" ");
                int position = post_content.getSelectionEnd();
                for (int i = 0; i < chooseUserInfos.size(); i++) {
                    position = position > 0 ? position - 1 : 0;
                    endPosition = position+1;
                    editable.replace(position, endPosition, mentionSpannable(chooseUserInfos.get(i)));
                    editable.append(" ");
                    if(i != chooseUserInfos.size()-1){
                        editable.append(" ");
                    }
                    position = post_content.getSelectionEnd();
                }
                post_content.setSelection(post_content.getEditableText().length());
            }
        }else if(requestCode == REQUEST_AT_LOOK_WITH_SIGN){
            if (data != null && data.getParcelableExtra("user") != null) {
                UserInfo userInfo = data.getParcelableExtra("user");
                int position = post_content.getSelectionEnd();
                SpannableString spannableString = mentionSpannable(userInfo);
                position = position > 0 ? position - 1 : 0;
                int endPosition = position+1;
                post_content.getEditableText().replace(position, endPosition, spannableString);
                post_content.getEditableText().append(" ");
                post_content.setSelection(post_content.getEditableText().length());
            }
        }else if (requestCode == REQUEST_LOCATION) {
            if (data != null) {
                choosePoiItem = (PoiItem) data.getParcelableExtra(ChooseLocationActivity.BUNDLE_RESULT);
                if (choosePoiItem != null) {
                    if (choosePoiItem instanceof NotShowPoiItem) {
                        location_tx.setText(getString(R.string.click_to_choose));
                        location_tx.setTextColor(getResources().getColor(R.color.color_text_hint));
                    } else {
                        if(TextUtils.isEmpty(choosePoiItem.getTitle())){
                            location_tx.setText(getString(R.string.click_to_choose));
                            location_tx.setTextColor(getResources().getColor(R.color.color_text_hint));
                        }else {
                            location_tx.setText(choosePoiItem.getTitle());
                            location_tx.setTextColor(getResources().getColor(R.color.login_btn_bg_color));
                        }
                    }
                }
            }
        } else if (requestCode == REQUEST_WHO_LOOK) {
            if (data != null) {
                chooseWhoLookType = data.getIntExtra("type", WhoLookActivity.WHO_LOOK_TYPE_PUBLIC_ALL);
                switch (chooseWhoLookType) {
                    case WhoLookActivity.WHO_LOOK_TYPE_PUBLIC_ALL:
                        title_look.setText(getString(R.string.who_look_text));
                        who_look_tx.setText(getString(R.string.public_text));
                        break;
                    case WhoLookActivity.WHO_LOOK_TYPE_PUBLIC_FRIENDS:
                        title_look.setText(getString(R.string.who_look_text));
                        who_look_tx.setText(getString(R.string.only_visible_to_friends));
                        break;
                    case WhoLookActivity.WHO_LOOK_TYPE_PRIVTE:
                        title_look.setText(getString(R.string.who_look_text));
                        who_look_tx.setText(getString(R.string.private_text));
                        break;
                    case WhoLookActivity.WHO_LOOK_TYPE_ALLOW_VISIBLE:
                    case WhoLookActivity.WHO_LOOK_TYPE_DISALLOW_VISIBLE:
                        if (data.getSerializableExtra("users") != null) {
                            chooseUsers = (ArrayList<UserInfo>) data.getSerializableExtra("users");
                        } else {
                            chooseUsers = null;
                        }
                        if (data.getSerializableExtra("groups") != null) {
                            groupInfos = (ArrayList<ChatInfo>) data.getSerializableExtra("groups");
                        } else {
                            groupInfos = null;
                        }
                        if (data.getSerializableExtra("tags") != null) {
                            chooseTags = (ArrayList<UserTags>) data.getSerializableExtra("tags");
                        } else {
                            chooseTags = null;
                        }
                        showTextByList(chooseUsers, groupInfos, chooseTags, who_look_tx);
                        if (chooseWhoLookType == WhoLookActivity.WHO_LOOK_TYPE_ALLOW_VISIBLE) {
                            title_look.setText(getString(R.string.who_can_not_see));
                        } else {
                            title_look.setText(getString(R.string.who_look_text));
                        }
                        break;
                }
            }
        } else {

            onActivityResultForPostCircleMedia(mediaStoreCompat, PostCircleActivity.this, requestCode, resultCode, data, PostCircleActivity.this);
        }
    }

    private SpannableString mentionSpannable(UserInfo userInfo) {
        String text = String.format("@%s",userInfo.displayName());
        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new CircleMentionSpan(userInfo.id,null), 0, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    private SpannableString mentionSpannable(CircleTopicInfo topicInfo) {
        String text = String.format("#%s",topicInfo.name);
        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new CircleMentionSpan(topicInfo.id,topicInfo), 0, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    @Override
    public void onSuccess(ArrayList<MediaInfo> mediaInfos) {
        totalMediaInfos.remove(addMediaBtnInfo);
        if (mediaInfos != null && mediaInfos.size() > 0) {
            notifyMediaInfo(mediaInfos);
            totalMediaInfos.addAll(mediaInfos);
            if (totalMediaInfos.size() < Constants.MAX_CIRCLE_IMAGE_COUNT && !mediaInfos.get(0).isVideo()) {
                totalMediaInfos.add(addMediaBtnInfo);
            }
            chooseAdapter.notifyDataSetChanged();
        }
    }

    private void notifyMediaInfo(ArrayList<MediaInfo> mediaInfos) {
        if (Common.isEmpty(mediaInfos)) {
            return;
        }
        for (MediaInfo mediaInfo : mediaInfos) {
            if (mediaInfo.isVideo()) {
                VideoParam videoParam = MediaUtils.getVideoParam(mediaInfo.getMediaPath());
                if (videoParam != null) {
                    mediaInfo.setWidth(videoParam.getWidth());
                    mediaInfo.setHeight(videoParam.getHeight());
                    mediaInfo.setDuration(videoParam.getDuration());
                }
            } else {
                GlideApp.with(this)
                        .asBitmap()
                        .load(mediaInfo.getMediaPath())
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                mediaInfo.setWidth(resource.getWidth());
                                mediaInfo.setHeight(resource.getHeight());
                            }
                        });
            }
        }
    }

    @Override
    public void onCancle() {

    }

    private final int REQUEST_USERS = 111;
    private final int REQUEST_LOCATION = 112;
    private final int REQUEST_WHO_LOOK = 113;
    private final int REQUEST_AT_LOOK = 114;
    private final int REQUEST_AT_LOOK_WITH_SIGN = 115;

    @OnClick({R.id.add_user_btn, R.id.who_look_btn, R.id.location_btn,R.id.topicBtn,R.id.fouceBtn})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_user_btn:
                startActivityForResult(MobileContactHomeActivity.getActivityForResult(this, 3, mChooseUsers), REQUEST_USERS);
                break;
            case R.id.who_look_btn:
                WhoLookActivity.chooseWhoLook(this, REQUEST_WHO_LOOK, chooseWhoLookType, chooseUsers, groupInfos, chooseTags);
                break;
            case R.id.location_btn:
                ChooseLocationActivity.chooseLocation(this, REQUEST_LOCATION, choosePoiItem);
                break;
            case R.id.topicBtn:
                showTopicDialog(false,view);
                break;
            case R.id.fouceBtn:
                startActivityForResult(MobileContactHomeActivity.getActivityForResult(PostCircleActivity.this, 3, null), REQUEST_AT_LOOK);
                break;
        }
    }
    private List<CircleTopicInfo> mTopicInfos = new ArrayList<>();
    private void loadTopicInfos(boolean showDialog){
        if(showDialog){
            showProgress();
        }
        TelegramManager.getTelegramManager().getHotTopic(this, 200, new TgResultBlock<List<CircleTopicInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<CircleTopicInfo> obj) {
                if(!Common.isEmpty(obj)){
                    mTopicInfos.addAll(obj);
                }else if(showDialog){
                    hideProgress();
                    ToastUtils.showShort(getString(R.string.request_error));
                }

            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                if(showDialog){
                    hideProgress();
                    ToastUtils.showShort(getString(R.string.request_error));
                }
            }
        });
    }

    private void insertTopicInfo(final boolean isSign,CircleTopicInfo circleTopicInfo){
        topicStartIndex = -1;
        if(!isSign){
            post_content.getEditableText().append(" ");
        }
        int position = post_content.getSelectionEnd();
        SpannableString spannableString = mentionSpannable(circleTopicInfo);
        position = position > 0 ? position - 1 : 0;
        int endPosition = position+1;
        post_content.getEditableText().replace(position, endPosition, spannableString);
        post_content.getEditableText().append(" ");
        post_content.setSelection(post_content.getEditableText().length());
    }

    private void replaceTopicInfo(CircleTopicInfo circleTopicInfo,int position,int endPosition){
        topicStartIndex = -1;
        SpannableString spannableString = mentionSpannable(circleTopicInfo);
        post_content.getEditableText().replace(position, endPosition, spannableString);
        post_content.setSelection(post_content.getEditableText().length());
    }

    private CircleTopicAttachDialog mTopicSelectDialog = null;
    private void showTopicDialog(final boolean isSign,View view){
        if(Common.isEmpty(mTopicInfos)){
            loadTopicInfos(false);
            return;
        }
        if(mTopicSelectDialog==null){
            mTopicSelectDialog = new CircleTopicAttachDialog(this);
        }
        mTopicSelectDialog.setTopicInfos(mTopicInfos);
        mTopicSelectDialog.setListener(new OnItemSelectListener<CircleTopicInfo>() {
            @Override
            public void onItemSelect(CircleTopicInfo circleTopicInfo, int s) {
                insertTopicInfo(isSign,circleTopicInfo);
            }
        });
        if(mTopicSelectDialog.isShow()){
            return;
        }
        int[] locations = new int[2];
        view.getLocationInWindow(locations);
        new XPopup.Builder(this)
                .atView(view)
                .hasShadowBg(false)
                .isDestroyOnDismiss(true)
                .offsetX(-locations[0])
                .popupAnimation(PopupAnimation.NoAnimation)
                .popupPosition(PopupPosition.Bottom)
                .asCustom(mTopicSelectDialog)
                .show();
    }

    private MediaInfo addMediaBtnInfo = new MediaInfo();


    public static class ChooseMediaAdapter extends BaseQuickAdapter<MediaInfo, BaseViewHolder> implements MyItemTouchCallback.ItemTouchAdapter {
        private PostCircleActivity activity;
        public ChooseMediaAdapter(PostCircleActivity activity,@Nullable List<MediaInfo> data) {
            super(R.layout.item_circle_media_info, data);
            this.activity = activity;
        }

        @Override
        protected void convert(@NotNull BaseViewHolder helper, MediaInfo mediaInfo) {
            boolean isEnd = getItemCount() == (helper.getAdapterPosition()+1);
            ImageView photo_image_view = helper.getView(R.id.photo_image_view);
            if(isEnd&&mediaInfo.isAddBtnType()){
                helper.setGone(R.id.video_tag,true);
                helper.setGone(R.id.delete_button,true);
                helper.setGone(R.id.add_user_btn,false);
                photo_image_view.setImageDrawable(null);
            }else{
                helper.setGone(R.id.delete_button,false);
                helper.setGone(R.id.video_tag,!mediaInfo.isVideo());
                helper.setGone(R.id.add_user_btn,true);
                GlideApp
                        .with(getContext())
                        .load(mediaInfo.getMediaPath())
                        .transforms(new CenterCrop(), new RoundedCorners(DensityUtil.dp2px(5)))
                        .into(photo_image_view);
                helper.getView(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean isVideo = mediaInfo.isVideo();
                        removeAt(helper.getAdapterPosition());
                        if(isVideo){
                            activity.totalMediaInfos.add(activity.addMediaBtnInfo);
                            notifyDataSetChanged();
                        }else{
                            if(!activity.totalMediaInfos.contains(activity.addMediaBtnInfo)){
                                activity.totalMediaInfos.add(activity.addMediaBtnInfo);
                                notifyDataSetChanged();
                            }
                        }
                    }
                });
            }
        }

        @Override
        public void onMove(int fromPosition, int toPosition) {
            if (activity.totalMediaInfos.contains(activity.addMediaBtnInfo)&&(fromPosition==getData().size()-1 || toPosition==getData().size()-1)){
                return;
            }
            if (fromPosition < toPosition) {
                for (int i = fromPosition; i < toPosition; i++) {
                    Collections.swap(getData(), i, i + 1);
                }
            } else {
                for (int i = fromPosition; i > toPosition; i--) {
                    Collections.swap(getData(), i, i - 1);
                }
            }
            notifyItemMoved(fromPosition, toPosition);
        }

        @Override
        public void onSwiped(int position) {

        }
    }

    private ChooseMediaAdapter chooseAdapter = new ChooseMediaAdapter(this,totalMediaInfos);

    private void showTextByList(List<UserInfo> userInfos, List<ChatInfo> chatInfos, List<UserTags> userTags, TextView textView) {
        StringBuilder stringBuilder = new StringBuilder();
        boolean preAppend = false;
        if (userInfos != null && userInfos.size() > 0) {
            int length = userInfos.size();
            for (int i = 0; i < length; i++) {
                UserInfo userInfo = userInfos.get(i);
                stringBuilder.append(userInfo.displayName());
                if (i != (length - 1)) {
                    stringBuilder.append("，");
                }
            }
            preAppend = true;
        }
        if (chatInfos != null && chatInfos.size() > 0) {
            if (preAppend) {
                stringBuilder.append(";");
            }
            int length = chatInfos.size();
            for (int i = 0; i < length; i++) {
                ChatInfo chatInfo = chatInfos.get(i);
                stringBuilder.append(chatInfo.title);
                if (i != (length - 1)) {
                    stringBuilder.append("，");
                }
            }
            preAppend = true;
        } else {
            preAppend = false;
        }
        if (userTags != null && userTags.size() > 0) {
            if (preAppend) {
                stringBuilder.append(";");
            }
            int length = userTags.size();
            for (int i = 0; i < length; i++) {
                UserTags tags = userTags.get(i);
                stringBuilder.append(tags.name);
                if (i != (length - 1)) {
                    stringBuilder.append("，");
                }
            }
        }
        textView.setText(stringBuilder.toString());
    }

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_post_circle;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}
